package com.example.demo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 设置跨域，让前端允许访问后台的接口
 */
@Configuration
public class CORSConf implements WebMvcConfigurer {
    @Value("${uploadPath}")
    String uploadPath;
    //配置虚拟路径和实体路径的映射关系
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/***")
                .addResourceLocations("file:"+uploadPath);
        registry.addResourceHandler("/avatar/***")
                .addResourceLocations("file:"+uploadPath+"avatar/");
        registry.addResourceHandler("/circle/***")
                .addResourceLocations("file:"+uploadPath+"circle/");
        registry.addResourceHandler("/banner/***")
                .addResourceLocations("file:"+uploadPath+"banner/");
    }
    //配置跨域的
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")      // 设置映射
                .allowedOrigins("*")        // 设置域
                .allowedMethods("*")               // 设置请求的方式GET、POST等
                .allowedHeaders("*");              // 设置头
    }
    @Bean
    public  MyInterceptor getMyInterceptor(){
        return new MyInterceptor();
    }
    //添加了拦截请求的代码
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getMyInterceptor())//配置自定义的拦截器
                .addPathPatterns("/**/**")//要拦截的请求路径，**表示我们拦截所有的请求路径
                .excludePathPatterns("/login","/getCode","/register","/admin/login");//除了带有login路径的请求路径不拦截

    }
}